/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.ap.web;

import java.io.File;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.ap.entity.PaymentApproval;
import com.jeeplus.modules.ap.entity.PaymentDetil;
import com.jeeplus.modules.ap.entity.ProcurementApplication;
import com.jeeplus.modules.ap.service.PaymentApprovalService;
import com.jeeplus.modules.ap.util.FksqPrint;
import com.jeeplus.modules.infor.entity.*;
import com.jeeplus.modules.infor.service.DepartmentService;
import com.jeeplus.modules.infor.service.ProjectService;
import com.jeeplus.modules.infor.service.StaffService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tms.entity.TmsWaybill;
import com.jeeplus.modules.tms.util.FileUtil;
import com.jeeplus.modules.tms.util.PrintWayBill;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.ap.entity.PaymentApplication;
import com.jeeplus.modules.ap.service.PaymentApplicationService;

/**
 * 付款申请Controller
 * @author 李超辉
 * @version 2018-12-12
 */
@Controller
@RequestMapping(value = "${adminPath}/ap/paymentApplication")
public class PaymentApplicationController extends BaseController {

	@Autowired
	private PaymentApplicationService paymentApplicationService;
	@Autowired
	private StaffService staffService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private PaymentApprovalService paymentApprovalService;
	@ModelAttribute
	public PaymentApplication get(@RequestParam(required=false) String id) {
		PaymentApplication entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = paymentApplicationService.get(id);
		}
		if (entity == null){
			entity = new PaymentApplication();
		}
		return entity;
	}


	/**
	 * 调用打印页面
	 */
	@RequestMapping(value = "dayin")
	public String dayin(HttpServletRequest request, PaymentApplication paymentApplication, Model model) throws Exception {

		//模版文件目录
		String templateFile = request.getSession().getServletContext().getRealPath("static/common/pdf/stenail/fksq.pdf");

		//要合并的pdf所在文件夹
		String folder = request.getSession().getServletContext().getRealPath("static/common/pdf/example/");

		FksqPrint print=new FksqPrint();
		//用于存放需要合并的pdf文件名
		List<String> filelist = new ArrayList<String>();
			//时间戳命名要合并的pdf并加入list
			String filewei = "fksq"+new Date().getTime() + ".pdf";
			//要合并的pdf目录
			String outFile = folder + "/"+filewei;
			File file = new File(outFile);
			if (!file.exists()) {
				try {
					file.createNewFile();
					System.out.println("创建成功!");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		PaymentApproval pp=new PaymentApproval();
		pp.setFksq(paymentApplication.getId());
		List<PaymentApproval> list=paymentApprovalService.findList(pp);
			print.updatePdfa(paymentApplication,list, templateFile, file);
			filelist.add(filewei);
			//}





		//合并后pdf所在文件夹
		String outPdfFileqian = request.getSession().getServletContext().getRealPath("static/common/pdf/print/");
		//合并后pdf文件目录
		String outPdfFile = outPdfFileqian+"/fksq"+new Date().getTime() + ".pdf";
		//合并pdf方法
		print.mergePdf(folder, outPdfFile,filelist);
//定时删除合并前的文件以及合并后的文件
		Timer timer = new Timer();//实例化Timer类
		timer.schedule(new TimerTask() {
			public void run() {
				try {
					FileUtil.deleteFile(outPdfFile);
					for (int i = 0; i < filelist.size(); i++){
						FileUtil.deleteFile(folder + File.separator + filelist.get(i));
						System.out.println("删除文件成功");}

				} catch (Exception e) {

				} finally {
					this.cancel();
				}

			}
		}, 50000);//五万毫秒 50秒
		//将合并后的pdf目录传到jsp供读取
		request.setAttribute("outPdfFile",outPdfFile);
		return "modules/ap/print/pdf";
	}

	/**
	 * 付款申请列表页面
	 */
	@RequiresPermissions("ap:paymentApplication:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/ap/paymentApplicationList";
	}
	/**
	 * 付款申请列表页面（报表）
	 */
	@RequiresPermissions("ap:paymentApplication:list")
	@RequestMapping(value = "list1")
	public String list1() {
		return "modules/ap/2/paymentApplicationList";
	}

	/**
	 * 付款申请列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:paymentApplication:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(PaymentApplication paymentApplication, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(!UserUtils.getUseroffice().equals("总部")){
			paymentApplication.setPro(UserUtils.getUseroffice());
		}
		Page<PaymentApplication> page = paymentApplicationService.findPage(new Page<PaymentApplication>(request, response), paymentApplication);
		return getBootstrapData(page);
	}
	/**
	 * 付款申请列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:paymentApplication:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(PaymentApplication paymentApplication, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(!UserUtils.getUseroffice().equals("总部")){
			paymentApplication.setPro(UserUtils.getUseroffice());
		}
		paymentApplication.setStatus("总经理已审批");
		Page<PaymentApplication> page = paymentApplicationService.findPage(new Page<PaymentApplication>(request, response), paymentApplication);
		return getBootstrapData(page);
	}
	/**
	 * 查看，增加，编辑付款申请表单页面
	 */
	@RequiresPermissions(value={"ap:paymentApplication:view","ap:paymentApplication:add","ap:paymentApplication:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(PaymentApplication paymentApplication, Model model) {
		if(paymentApplication.getIsNewRecord()){
			paymentApplication.setStatus("已创建");
			paymentApplication.setFkzt("未付款");
			paymentApplication.setPro(UserUtils.getUseroffice());
			Department d=new Department();
			d.setProject(projectService.findUniqueByProperty("name",UserUtils.getUseroffice()));
			d=departmentService.findList(d).get(0);
			d=departmentService.get(d.getId());
			paymentApplication.setBm(d.getName());
			paymentApplication.setDate(new Date());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String code=UserUtils.getUserAre()+sdf.format(new Date());
			PaymentApplication p=new PaymentApplication();
			p.setCode(code);
			List<PaymentApplication> list=paymentApplicationService.findList(p);
			if(list==null||list.size()<1){
				paymentApplication.setCode(code+"001"+"FKSQ");
			}else{
				if(list.size()/10==0){
					paymentApplication.setCode(code+"00"+(list.size()+1)+"FKSQ");
				}else
				if(list.size()/100==0){
					paymentApplication.setCode(code+"0"+(list.size()+1)+"FKSQ");
				}else{paymentApplication.setCode(code+(list.size()+1)+"FKSQ");}

			}
			Staff staff =new Staff();
			staff.setProjectName(UserUtils.getUseroffice());
			List<Staff> l=staffService.findList(staff);
			for(Staff s:l){
				if(staffService.get(s.getId()).getPosition().getName().contains("财务")){
					paymentApplication.setSqr(s.getName());
				}
			}
		}
		model.addAttribute("paymentApplication", paymentApplication);
		return "modules/ap/paymentApplicationForm";
	}


	@ResponseBody
	@RequestMapping(value = "detail")
	public PaymentApplication detail(String id) {
		PaymentApplication p=paymentApplicationService.get(id);
		PaymentApproval pp=new PaymentApproval();
		pp.setFksq(id);
		List<PaymentApproval> list=paymentApprovalService.findList(pp);
		p.setApprovalList(list);
		return p;
	}
	/**
	 * 保存付款申请
	 */
	@ResponseBody
	@RequiresPermissions(value={"ap:paymentApplication:add","ap:paymentApplication:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(PaymentApplication paymentApplication, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, paymentApplication)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		List<PaymentDetil> list=paymentApplication.getPaymentDetilList();
		int zje=0;
		for(PaymentDetil p:list){
			zje+=Integer.parseInt(p.getZjhs());
		}
		paymentApplication.setJe(zje+"");
		paymentApplication.setXc(list.size()+"");
		paymentApplicationService.save(paymentApplication);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存付款申请成功");
		return j;
	}
	/**
	 * 确认提交
	 */
	@ResponseBody
	@RequestMapping(value = "qr")
	public AjaxJson qr(PaymentApplication paymentApplication, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		paymentApplication.setStatus("已确认待审批");
		paymentApplicationService.save(paymentApplication);
		PaymentApproval p=new PaymentApproval();
		p.setDate(new Date());
		p.setAction("确认提交");
		p.setFksq(paymentApplication.getId());
		p.setPerson(UserUtils.getUserName());
		paymentApprovalService.save(p);
		j.setMsg("确认成功");
		return j;
	}
	/**
	 * 确认提交
	 */
	@ResponseBody
	@RequestMapping(value = "fkqr")
	public AjaxJson fkqr(PaymentApplication paymentApplication, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		paymentApplication.setFkzt("已付款");
		paymentApplicationService.save(paymentApplication);
		j.setMsg("确认成功");
		return j;
	}
	@RequestMapping(value = "updateStatus")
	@ResponseBody
	public String updateStatus(PaymentApplication paymentApplication,String yj,HttpServletResponse response,HttpServletRequest request) {
		String position= UserUtils.getposition();
		if(position.equals("办事处经理")){
			paymentApplication.setStatus("经理已审批");
		}
		if(position.contains("总监")){
			paymentApplication.setStatus("总监已审批");
		}NumberFormat nf = NumberFormat.getInstance();
		if(position.equals("总经理")){
			paymentApplication.setStatus("总经理已审批");
		}
		PaymentApproval p=new PaymentApproval();
		p.setDate(new Date());
		p.setAction("审批通过");
		p.setFksq(paymentApplication.getId());
		p.setPerson(UserUtils.getUserName());
		p.setReson(yj);
		paymentApprovalService.save(p);
		paymentApplicationService.save(paymentApplication);

		return "sesst";
	}
	@ResponseBody
	@RequestMapping(value = "bh")
	public AjaxJson bh(PaymentApplication paymentApplication,String yj, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		paymentApplication.setStatus("审核未通过");
		paymentApplicationService.save(paymentApplication);
		PaymentApproval p=new PaymentApproval();
		p.setDate(new Date());
		p.setAction("驳回");
		p.setFksq(paymentApplication.getId());
		p.setPerson(UserUtils.getUserName());
		p.setReson(yj);
		paymentApprovalService.save(p);
		j.setMsg("驳回成功");
		return j;
	}
	/**
	 * 删除付款申请
	 */
	@ResponseBody
	@RequiresPermissions("ap:paymentApplication:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(PaymentApplication paymentApplication, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		paymentApplicationService.delete(paymentApplication);
		j.setMsg("删除付款申请成功");
		return j;
	}
	
	/**
	 * 批量删除付款申请
	 */
	@ResponseBody
	@RequiresPermissions("ap:paymentApplication:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			paymentApplicationService.delete(paymentApplicationService.get(id));
		}
		j.setMsg("删除付款申请成功");
		return j;
	}
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("ap:paymentApplication:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(PaymentApplication paymentApplication, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "付款申请"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<PaymentApplication> page = paymentApplicationService.findPage(new Page<PaymentApplication>(request, response, -1), paymentApplication);
    		new ExportExcel("付款申请", PaymentApplication.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出付款申请记录失败！失败信息："+e.getMessage());
		}
			return j;
    }
	/**
	 * 导入Excel数据
	 */
	@RequiresPermissions("ap:paymentApplication:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<PaymentApplication> list = ei.getDataList(PaymentApplication.class);
			for (PaymentApplication paymentApplication : list){
				try{
					paymentApplicationService.save(paymentApplication);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条付款申请记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条付款申请记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入付款申请失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/paymentApplication/?repage";
    }
	
	/**
	 * 下载导入付款申请数据模板
	 */
	@RequiresPermissions("ap:paymentApplication:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "付款申请数据导入模板.xlsx";
    		List<PaymentApplication> list = Lists.newArrayList(); 
    		new ExportExcel("付款申请数据", PaymentApplication.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/paymentApplication/?repage";
    }

}